import java.awt.event.*;
import java.io.*;

class Control {
    private String FilePath;

    Control(String st) {
        FilePath = st;
    }
    
    private void SaveToFile(String st) {
        FileWriter FW = null;
        try { 
            FW = new FileWriter(FilePath);        
            FW.write(st);
        }
        catch (IOException e) {
            System.out.println("Exception when trying to save file" );
        }
        
        finally {
            if (FW != null) {
                try {
                    FW.close(); 
                }
                catch (IOException e) {
                    System.out.println("Exception when trying to save file" );
                }
            }
        }
    }

    private String LoadFromFile() {
        String buf,st = "";        
        BufferedReader BR = null;
        try {
            BR = new BufferedReader(new FileReader(FilePath));
            while ( (buf = BR.readLine()) != null) {
                st += (buf+"\n");
            }
        }
        
        catch(IOException e) {
            System.out.println("Exception when trying to read file" );
        }
        finally {
            if (BR != null) {
                try {
                    BR.close();
                }
                catch (IOException e) {
                    System.out.println("Exception when trying to read file" );
                }
            }
        }
        return st;
    }
        
    public Widgets CreateGUI() {
        return new Widgets();
    }

    public void SetEvents(final Widgets W) {
        W.SetSaveButtonEvent(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    SaveToFile(W.GetText());
                }
            });

        W.SetLoadButtonEvent(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    W.SetText(LoadFromFile());
                }
            }); 
        W.SetCloseOperation(new WindowListener () {
                public void windowClosing(WindowEvent event) {
                    event.getWindow().setVisible(false);
                    (new File(FilePath)).delete();
                    System.out.println("Bye!");
                    System.exit(0);
                }
                public void windowDeactivated(WindowEvent event) {
                }
                public void windowDeiconified(WindowEvent event) {
                }
                public void windowIconified(WindowEvent event) {
                }
                public void windowOpened(WindowEvent event) {
                }
                public void windowActivated(WindowEvent event) {
                }
                public void windowClosed(WindowEvent event) {
                }
            });
    }

    public void StartAll(Widgets W) {
        W.MainFrameShow();
    }
}